local addon = AspireML
local Handout = addon:NewModule("Handout")
_G.AspireML.HandoutLoot = Handout

local _G = _G


local function GetPlayerIndex(name)
	-- Gets the loot candidate index for use to handout
	for i = 1, 40 do
		local candidate = GetMasterLootCandidate(i)
		if (candidate and candidate == name) then
			return i
		end
	end
	return nil
end

local function GetLootIndex(item)
	-- Gets the index of selected item
	for i = 1, GetNumLootItems() do
		local link = GetLootSlotLink(i)
		if(link == item) then
			return i
		end
	end
	return nil
end

-- Note: Item should be item LINK, string passed to player should be default from unitname (i.e. dont pass lowercase names)
function Handout:LootToPlayer(item, player)
	local ci = GetPlayerIndex(player)
	if not ci then
		addon:Print(("Error: %s was not able to receive this item. (Out of range or not in the loot list)"):format(player))
		return nil
	end
	
	local li = GetLootIndex(item)
	assert(li, (("Error: %s was not found in loot window."):format(item)))
	
	if(ci and li) then
		-- We should be good to go, loot the item to player
		GiveMasterLoot(li, ci);
	end
end